<?php

namespace app\home\controller;

use app\common\controller\Home;
use app\common\library\Email;

class Business extends Home
{

    protected $BusinessModel = null;

    protected $EmsModel = null;

    protected $ReceiveModel = null;

    protected $CouponModel = null;

    //点赞模型
    protected $LikeModel = null;

    //订单模型
    protected $OrderModel = null;

    protected $SubjectModel = null;

    //课程分类模型
    protected $CategoryModel = null;

    //评论模型
    protected $CommentModel = null;

    protected $CommissionModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('business.Business');

        $this->EmsModel = model('Ems');

        $this->ReceiveModel = model('coupon.Receive');

        $this->CouponModel = model('coupon.Coupon');

        $this->LikeModel = model('subject.Like');

        $this->OrderModel = model('subject.Order');

        $this->SubjectModel = model('subject.Subject');

        $this->CategoryModel = model('subject.Category');

        $this->CommentModel = model('subject.Common');

        $this->CommissionModel = model('business.Commission');
    }

    public function index()
    {
        return view();
    }

    public function profile()
    {

        if ($this->request->isPost()) {

            //接收参数
            $params = $this->request->param();

            // halt($param);

            $salt = build_randstr();

            $data = [
                'id' => $this->auth->id,
                'nickname' => trim($params['nickname']),
                'mobile' => trim($params['mobile']),
                'email' => trim($params['email']),
                'gender' => $params['gender'],
            ];

            // 修改用户认证状态
            if ($data['email'] != $this->auth->email) {
                $data['auth'] = 0;
            }

            // 获取密码
            $password = isset($params['password']) ? trim($params['password']) : '';

            // 处理密码
            if ($password) {
                $repass = md5($password . $this->auth->salt);

                if ($repass == $this->auth->password) {
                    $this->error("原密码和新密码相同");
                }

                // 生成密码盐
                $salt = build_randstr();

                // 拼接并且加密
                $password = md5($password . $salt);

                $data['salt'] = $salt;
                $data['password'] = $password;
            }


            // 处理地区
            if (!empty($params['code'])) {
                // 根据code获取相应id路径的值,查询数据库信息
                $path = model('Region')->where(['code' => $params['code']])->value('parentpath');

                if (empty($path)) {
                    $this->error('所选地区不存在');
                }

                $pathArr = explode(",", $path);

                $data['province'] = $pathArr[0] ?? null;
                $data['city'] = $pathArr[1] ?? null;
                $data['district'] = $pathArr[2] ?? null;
            } else {

                $this->error("请选择地区");
            }

            // 处理头像
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = build_upload('avatar');

                if ($avatar === 0) {
                    $this->error($avatar['msg']);
                } else {
                    $data['avatar'] = $avatar['data'];
                }
            }

            // 更新到数据表
            $result = $this->BusinessModel->validate('common/business/Business.profile')->isUpdate(true)->save($data);


            if ($result === false) {
                $this->error($this->BusinessModel->getError());
            } else {
                $this->success('更新基本资料成功', url('/home/business/index'));
            }
        }


        return $this->fetch();
    }


    public function email()
    {
        if (empty($this->auth->email)) {
            $this->error('请去基本资料添加邮箱');
        }

        // 0 => 未认证 1 => 已认证
        if ($this->auth->auth == 1) {
            $this->success('您已认证了，无须重复认证');
        }

        if ($this->request->isPost()) {
            $code = $this->request->param('code', '', 'trim');
            $email = $this->request->param('email', '', 'trim');

            // 验证码是否为空
            if (empty($code)) {
                $this->error('验证码不能为空');
            }

            // 查询数据表是否存在该条记录
            $ems = $this->EmsModel->where(['email' => $email, 'code' => $code, 'event' => 'emailAuth'])->find();

            if (empty($ems)) {
                $this->error('验证码错误');
            }

            // 开启事务
            $this->BusinessModel->startTrans();
            $this->EmsModel->startTrans();

            $BusinessData = [
                'id' => $this->auth->id,
                'auth' => 1
            ];

            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === false) {
                $this->error('更新用户认证状态失败');
            }

            // 删除当前记录
            $EmsStatus = $this->EmsModel->destroy($ems['id']);

            if ($EmsStatus === false) {
                $this->BusinessModel->rollback();
                $this->error('删除验证码失败');
            }

            if ($BusinessStatus === false || $EmsStatus === false) {
                $this->BusinessModel->rollback();
                $this->EmsModel->rollback();
                $this->error('认证失败');
            } else {
                $this->BusinessModel->commit();
                $this->EmsModel->commit();
                $this->success('认证成功', url('/home/business/index'));
            }
        }

        return $this->fetch();
    }


    // 发送邮件
    public function send()
    {
        if ($this->request->isAjax()) {

            $email = $this->request->param('email', '', 'trim');
            $email = empty($email) ? $this->auth->email : $email;

            if (empty($email)) {
                $this->error('邮箱不能为空');
            }

            if ($this->auth->auth == 1) {
                $this->error('您已认证了，无须重复认证');
            }

            // 开启事务
            $this->EmsModel->startTrans();

            // 先查询一下该邮箱过期验证码
            $DelStatus = $this->EmsModel->where(['email' => $email])->delete();

            if ($DelStatus === false) {
                $this->error('删除过期验证码失败');
            }

            // 实例化发送邮箱类
            $Email = new Email();

            // 生成随机验证码
            $code = build_randstr(6);

            // 定义邮件内容
            $content = "您的邮箱认证验证码：<b>{$code}</b>";

            // 需要把验证码存到数据表里
            $EmsData = [
                'event' => 'emailAuth', // 定义自定义事件名
                'email' => $email, // 接收人邮箱
                'code' => $code, // 验证码
                'times' => 1, // 验证次数
                'ip' => $this->request->ip(), // ip地址
            ];

            $EmsStatus = $this->EmsModel->validate('common/Ems')->save($EmsData);

            if ($EmsStatus === false) {

                // 新增验证码失败，告诉系统这边回滚前面操作成功的记录
                $this->EmsModel->rollback();

                // 返回错误信息
                $this->error($this->EmsModel->getError());
            }

            // 获取系统邮箱配置的发件人邮箱
            $FromEmail = config('site.mail_from');

            $result = $Email->subject('云平台认证')->from($FromEmail, '云平台')->message($content)->to($email)->send();

            if ($result === false) {
                $this->EmsModel->rollback();
                $this->error($Email->getError());
            }


            // 综合判断
            if ($DelStatus === false || $EmsStatus === false || $result === false) {
                // 回滚事务
                $this->EmsModel->rollback();
                $this->error('发送失败');
            } else {
                // 提交事件
                $this->EmsModel->commit();
                $this->success('发送成功', url('/home/business/index'));
            }
        }
    }


    public function coupon_list()
    {
        //获取课程id
        $subid = $this->request->param('subject', '', 'trim');
        cookie('subid', $subid,);

        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            $where = [];

            $business = $this->IsLogin(false);        //跳过登录验证,获取当前用户的id

            //判断用户是否已领取里优惠卷
            $list = $this->ReceiveModel->where(['busid' => $business['id']])->select();

            //查询数据总数
            $count = $this->ReceiveModel->where(['status' => '1'])->count();

            $juan = [];
            foreach ($list as $item) {
                $coupon = $this->CouponModel->where(['id' => $item['cid']])->select();

                $juan[] = $coupon;
            }
            $data = [
                'receive' => $list,
                'count' => $count,
                'list' => $juan
            ];

            if ($count) {
                $this->success('查询优惠卷成功', null, $data);
            } else {
                $this->error('暂无优惠卷', null, $data);
            }
        }
        return $this->fetch();
    }

    //用户课程绑定优惠卷
    public function buy()
    {
        if ($this->request->isAjax()) {
            // 获取课程id
            $subid = $_COOKIE['subid'];
            //获取优惠卷id
            $cid = $this->request->param('couponid', 0, 'trim');
            //获取用户id
            $busid = $this->auth->id;

            $scid = [
                'busid' => $busid,
                'subid' => $subid
            ];

            $receive = [
                'busid' => $busid,
                'cid' => $cid
            ];

            $likelist = $this->LikeModel->where($scid)->find();
            if ($likelist) {
                $likelist = $this->LikeModel->validate('common/subject/Like')->where($scid)->update(['cid' => $cid]);
            }
            $likelist = $this->LikeModel->where($scid)->find();

            if ($likelist) {
                $this->success("使用成功", null, $likelist);
            } else {
                $this->error("不能使用", null, $likelist);
            }
        }
        return $this->fetch();
    }


    public function order()
    {
        if ($this->request->isAjax()) {

            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            //用户id
            $busid = $this->auth->id;

            $orderlist = $this->OrderModel->where(['busid' => $busid])->page($page, $limit)->select();

            $count = $this->OrderModel->where(['busid' => $busid])->page($page, $limit)->count();

            $subject = [];
            $thumb_cdn = [];
            $total = [];
            $cateid = [];
            $comment = [];

            //查找课程
            foreach ($orderlist as $key) {
                $subidlist = $this->SubjectModel->where(['id' => $key['subid']])->find();
                $subject[] = $subidlist['title'];
                $thumb_cdn[] = $subidlist['thumb_cdn'];
                $total[] = $subidlist['price'];
                //查询课程分类
                $category = $this->CategoryModel->where(['id' => $subidlist['cateid']])->find();
                $cateid[] = $category['name'];
                //查询评论
                $commentid = $this->CommentModel->where(['busid' => $key['busid'], 'subid' => $key['subid']])->find();
                $comment[] = $commentid;
            }

            $data = [
                'list' => $orderlist,
                'count' => $count,
                'subject' => $subject,
                'thumb_cdn' => $thumb_cdn,
                'total' => $total,
                'cateid' => $cateid,
                'comment' => $comment
            ];

            if ($orderlist) {
                $this->success("订单存在", null, $data);
            } else {
                $this->error("订单不存在", null, $data);
            }
        }

        return $this->fetch();
    }

    //购买课程的评论
    public function comment()
    {
        $subid = $this->request->param('subject', '', 'trim');
        $busid = $this->auth->id;
        $data = [
            'subid' => $subid,
            'busid' => $busid
        ];
        if ($this->request->isPost()) {
            //获取评论信息
            $comment = $this->request->param('content', '', 'trim');
            if (!$comment) {
                $this->error("不可无评论");
            }
            //获取评分
            $rate = $this->request->param('rate', '', 'trim');
            //查找评论是否存在
            $subcomment = $this->CommentModel->where($data)->find();
            if ($subcomment) {
                $this->success("已评论，无需再次评论");
            }
            //获取订单id
            $order = $this->OrderModel->where($data)->find();
            if (!$order) {
                $this->error("订单不存在");
            }

            $datas = [
                'content' => $comment,
                'createtime' => time(),
                'busid' => $busid,
                'subid' => $subid,
                'rate' => $rate,
                'orderid' => $order['id']
            ];

            $subcomment = $this->CommentModel->save($datas);
            if ($subcomment) {
                $this->success("评论成功", url('/home/business/order'));
            }
        }

        $subject = $this->SubjectModel->where(['id' => $subid])->find();
        if (!$subject) {
            $this->error("课程不存在");
        }

        $comment = $this->CommentModel->where($data)->find();

        $this->assign([
            'subid' => $subject,
            'comment' => $comment
        ]);

        return $this->fetch();
    }

    //提现列表
    public function money()
    {
        if ($this->request->isAjax()) {
            $business = $this->auth->id;

            $Commission = $this->CommissionModel->where(['parentid' => $business])->select();

            $order = [];
            //提现值
            $amount = [];
            //是否提现
            $status = [];
            foreach ($Commission as $key) {
                $order[] = $key['orderid'];
                $amount[] = $key['amount'];
                $status[] = $key['status'];
            }

            //课程id
            $subid = [];
            $busid = [];
            //订单号
            $ordercode = [];
            //花费金额
            $total = [];
            //订单时间
            $time = [];
            foreach ($order as $id) {
                $orderlist = $this->OrderModel->where(['id' => $id])->find();
                $subid[] = $orderlist['subid'];
                $busid[] = $orderlist['busid'];
                $ordercode[] = $orderlist['code'];
                $total[] = $orderlist['total'];
                $time[] = $orderlist['createtime_text'];
            }

            //课程名字
            $subname = [];
            foreach ($subid as $key) {
                $subject = $this->SubjectModel->where(['id' => $key])->find();
                $subname[] = $subject['title'];
            }

            $data = [
                'code' => $ordercode,
                'subject' => $subname,
                'total' => $total,
                'time' => $time,
                'amount' => $amount,
                'status' => $status,
                'order' => $order
            ];

            if ($Commission) {
                $this->success("查询成功", null, $data);
            } else {
                $this->error("查询失败");
            }
        }
        return $this->fetch();
    }


    //提现
    public function commission()
    {
        if ($this->request->isAjax()) {
            $orderid = $this->request->param('orderid', 0, 'trim');
            $amount = $this->request->param('amount', 0, 'trim');
            $commission = $this->CommissionModel->where(['orderid' => $orderid])->update(['status' => 1]);

            $busid = $this->auth->id;

            $business = $this->BusinessModel->where(['id' => $busid])->find();

            $total = $business['money'] + $amount;

            $business = $this->BusinessModel->where(['id' => $busid])->update(['money' => $total]);
            if ($business) {
                $this->success("提现成功");
            }
        }

        return $this->fetch();
    }


    //我的课程
    public function course()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            $busid = $this->auth->id;

            $orderlist = $this->OrderModel->with(['sub'])->where(['busid' => $busid])->page($page, $limit)->select();
            $count = $this->OrderModel->with(['sub'])->where(['busid' => $busid])->page($page, $limit)->count();

            $subjectlist = [];
            foreach ($orderlist as $key) {
                $subject = $this->SubjectModel->with(['category', 'teacher'])->where(['subject.id' => $key['subid']])->find();
                $subjectlist[] = $subject;
            }


            $data = [
                'list' => $orderlist,
                'sublist' => $subjectlist,
                'count' => $count
            ];
            if ($orderlist) {
                $this->success("查询成功", null, $data);
            } else {
                $this->error("查询失败", null, $data);
            }
        }
        return $this->fetch();
    }


    //收藏
    public function collection()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $busid = $this->auth->id;

            $subid = $this->LikeModel->where(['busid' => $busid, 'collect' => 1])->page($page, $limit)->select();
            $count = $this->LikeModel->where(['busid' => $busid, 'collect' => 1])->page($page, $limit)->count();

            $subjectlist = [];
            foreach ($subid as $key) {
                $subject = $this->SubjectModel->with(['category', 'teacher'])->where(['subject.id' => $key['subid']])->find();
                $subjectlist[] = $subject;
            }


            $data = [
                'subject' => $subjectlist,
                'count' => $count
            ];

            if ($subject) {
                $this->success("查找成功", null, $data);
            } else {
                $this->error("查找失败");
            }
        }

        return $this->fetch();
    }
}
